import {
  ReqGetDepartment,
  ReqGetDoctor,
  ReqGetHospitalScheduleRule,
} from "@/api/hospital/hospitalList";
import {
  DeparmentItems,
  HospitalScheduleDoctorItems,
  HospitalScheduleRuleList,
} from "@/api/hospital/model/hospitalListTypes";
import {
  Button,
  Card,
  Col,
  message,
  Pagination,
  Row,
  Table,
  Tag,
  Tree,
} from "antd";
import { ColumnsType } from "antd/lib/table";
import React, { Key, useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";

export default function HospitalListSchedule() {
  // 声明表格结构
  let columns: ColumnsType<any> = [
    {
      title: "序号",
      render: (value, row, index) => {
        return index + 1;
      },
    },
    {
      title: "职称",
      dataIndex: "title",
    },
    {
      title: "号源时间",
      dataIndex: "workDate",
    },
    {
      title: "总预约数",
      dataIndex: "reservedNumber",
    },
    {
      title: "剩余预约数",
      dataIndex: "availableNumber",
    },
    {
      title: "挂号费(元)",
      dataIndex: "amount",
    },
    {
      title: "擅长技能",
      dataIndex: "skill",
    },
  ];
  // 计算出树状图的自定义高度
  let height =
    document.documentElement.clientHeight - 64 - 34 - 5 * 2 - 24 * 2 - 22 - 20;
  // 从url中获取医院id
  let { id } = useParams();
  // 声明一个科室的状态
  let [department, setDepartment] = useState<DeparmentItems>([]);
  // 声明一个展开节点的状态
  let [expandedKeys, setExpandedKeys] = useState<string[]>([]);
  // 声明一个当前页码的状态
  let [current, setCurrent] = useState(1);
  // 声明一个总数的状态
  let [total, setTotal] = useState(0);
  // 声明一个每页显示数量的状态
  let [pageSize, setPageSize] = useState(5);
  // 声明一个医院排班的状态
  let [hospitalSchedule, setHospitalSchedule] = useState<
    HospitalScheduleRuleList[]
  >([]);
  // 声明一个医生列表的状态
  let [doctors, setDoctors] = useState<HospitalScheduleDoctorItems>([]);
  // 声明一个医院名称的状态
  let [hosname, setHosname] = useState("");
  // 声明一个科室名称的状态
  let [depname, setDepname] = useState("");
  // 声明一个日期的状态
  let [workDate, setWorkDate] = useState("");
  // 声明一个科室编号的状态
  let [depcode, setDepcode] = useState("");
  // 声明一个获取医院科室的函数
  let getDepartment = async () => {
    // 获取所有科室
    let departments = await ReqGetDepartment(id as string);
    // 给每个一级科室添加禁用属性
    departments = departments.map((item) => {
      item.disabled = true;
      return item;
    });
    // 获取所有的科室编号
    let depcodes = departments.map((item) => {
      return item.depcode;
    });
    // 更新科室状态
    setDepartment(departments);
    // 更新树状结构展开的状态
    setExpandedKeys(depcodes);
    // 获取第一个默认选中的二级科室的编号
    let depcode = (departments[0].children as DeparmentItems)[0].depcode;
    // 获取第一个默认选中的二级科室的名称
    let depname = (departments[0].children as DeparmentItems)[0].depname;
    // 更新科室编号的状态
    setDepcode(depcode);
    // 更新科室名称的状态
    setDepname(depname);
  };

  // 声明一个获取医院排班的状态
  let getHospitalSchedules = async () => {
    try {
      // 获取第一个科室的未来的排班
      let hospitalSchedules = await ReqGetHospitalScheduleRule({
        page: current,
        limit: pageSize,
        hoscode: id as string,
        depcode,
      });
      // 更新排班的状态
      setHospitalSchedule(hospitalSchedules.bookingScheduleList);
      // 更新总数
      setTotal(hospitalSchedules.total);
      // 更新医院名称
      setHosname(hospitalSchedules.baseMap.hosname);
      // 获取工作日期
      let workDate = hospitalSchedules.bookingScheduleList[0].workDate;
      // 更新工作日期
      setWorkDate(workDate);
      let doctors = await ReqGetDoctor({
        hoscode: id as string,
        depcode,
        workDate,
      });
      // 更新医生状态
      setDoctors(doctors);
    } catch (e) {
      // 清空医院排班列表
      setHospitalSchedule([]);
      // 清空医生列表
      setDoctors([]);
      message.error("失败");
    }
  };

  // 声明一个获取医生列表的函数
  let getDoctor = async () => {
    // 获取某天医生的排班信息
    let doctors = await ReqGetDoctor({
      hoscode: id as string,
      depcode,
      workDate,
    });
    // 更新医生状态
    setDoctors(doctors);
  };

  let navigate = useNavigate();
  // 改变左侧科室的事件
  let select = async (selectedKeys: Key[], info: any) => {
    // 更新所点击的科室的名称和编号
    let depname = info.node.depname;
    let depcode = info.node.depcode;
    setDepcode(depcode);
    setDepname(depname);
  };
  // 改变工作日期的事件
  let changeDate = (workDate: string) => {
    return async () => {
      setWorkDate(workDate);
    };
  };

  useEffect(() => {
    getDepartment();
  }, []);

  useEffect(() => {
    if (!depcode) return;
    getHospitalSchedules();
  }, [current, pageSize, depcode, depname]);

  useEffect(() => {
    if (!workDate) return;
    getDoctor();
  }, [workDate]);
  return (
    <Card>
      {/* 路径导航 */}
      <div>
        选择 : {hosname} / {depname} / {workDate}
      </div>
      <div className="h-20"></div>
      <Row gutter={20}>
        <Col span={6}>
          <div
            style={{
              border: "1px solid #aaa",
              overflowY: "scroll",
              height: height,
            }}
          >
            <Tree
              // 选择节点
              onSelect={select}
              // 设置展开的树节点
              expandedKeys={expandedKeys}
              // 自定义节点 title、key的字段
              fieldNames={{
                title: "depname",
                key: "depcode",
              }}
              // 设置选中的树节点
              selectedKeys={[depcode]}
              // 树状结构
              treeData={department as []}
            />
          </div>
        </Col>
        <Col span={18}>
          {hospitalSchedule.map((item) => {
            return (
              <Tag
                color={item.workDate === workDate ? "green" : ""}
                key={item.workDate}
                onClick={changeDate(item.workDate)}
                style={{ cursor: "pointer" }}
              >
                <div>
                  {item.workDate} {item.dayOfWeek}
                </div>
                <div>
                  {item.availableNumber} / {item.reservedNumber}
                </div>
              </Tag>
            );
          })}
          <div className="h-20"></div>
          <Pagination
            current={current}
            total={total}
            pageSize={pageSize}
            onChange={async (page: number, pageSize: number) => {
              setCurrent(page);
              setPageSize(pageSize);
            }}
          />
          <div className="h-20"></div>
          <Table
            columns={columns}
            bordered
            dataSource={doctors}
            rowKey="id"
            pagination={false}
          ></Table>
          <div className="h-20"></div>
          <Button
            onClick={() => {
              navigate("/syt/hospital/hospitallist");
            }}
          >
            返回
          </Button>
        </Col>
      </Row>
    </Card>
  );
}
